package com.ggmc;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Sendmail {

	public void mail(String smtpHost, final String username, final String password, String to, String from, String subject, String htmlFile, String sAttachedFile) {

			// read the HTML source
			String htmlText="";
			
			// Get properties object
			Properties props = System.getProperties();

			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.host",smtpHost);
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.port", "26");
			//props.put("mail.debug", "true"); 
			
			try {
			//get session
			Session session = Session.getInstance(props,
					  new javax.mail.Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(username, password);
						}
					  });			

			MimeMessage message = new MimeMessage(session);  
	        message.setSubject(subject);  
	        message.setFrom(new InternetAddress(from));  
	        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  
	  
			String sTagImageStart = "src=\"";
			String sTagImageEnd = ">";
			String line;

			ArrayList<String> aUUID = new ArrayList<String>();
			ArrayList<String> aImgSrcLoc = new ArrayList<String>();

			FileReader fr;
			
				fr = new FileReader(htmlFile);
				BufferedReader br = new BufferedReader(fr);

				while((line = br.readLine()) != null)	{

					///find all occurrences
					for (int iTagImageStartIndex = -1; (iTagImageStartIndex = line.indexOf(sTagImageStart, iTagImageStartIndex + 1)) != -1; ) {

						int iTagImageEndIndex = line.indexOf(sTagImageEnd, iTagImageStartIndex);
						String sFoundImage = line.substring(iTagImageStartIndex, iTagImageEndIndex + 1);
						String sUUID = UUID.randomUUID().toString();
						line = line.replaceFirst(sFoundImage, "src=\"cid:" + sUUID + "\"" + sTagImageEnd);
					    String sImgSrcLoc = imgSrcLoc(sFoundImage);

					    ///save cid & image src location
					    aUUID.add(sUUID);
					    aImgSrcLoc.add(sImgSrcLoc);
					}
					htmlText += line;
				}
				br.close();
				        
	        //  
	        // This HTML mail have to 2 part, the BODY and the embedded image  
	        // 
	        MimeMultipart multipart = new MimeMultipart("related");  

	        // first part  (the html)  
	        BodyPart messageBodyPart = new MimeBodyPart(); 
	        //htmlText = "<H1>Ricky</H1><img src=\"cid:image1\"><img src=\"cid:image2\">"; 
	        messageBodyPart.setContent(htmlText, "text/html");  

	        // add it
	        multipart.addBodyPart(messageBodyPart);	        
		    
	        for (int i = 0; i < aUUID.size(); i++) {
		        // second part (the image)  
		        messageBodyPart = new MimeBodyPart();
		        DataSource fds = new FileDataSource(aImgSrcLoc.get(i));  
		        messageBodyPart.setDataHandler(new DataHandler(fds));  
		        messageBodyPart.setHeader("Content-ID","<" + aUUID.get(i) + ">");  
		        
		        // add it
		        multipart.addBodyPart(messageBodyPart);
	        }
	        
	        String[] attachmentsFiles = new String[]{
	        		  sAttachedFile
	          };

	        // THIS IS JUST FOR TESTING HTML EMBEDDING OF DIFFERENT TYPE OF ATTACMENTS.
	        if(sAttachedFile != null) {
	        StringBuilder sb = new StringBuilder();
		        for (String attachmentFileName : attachmentsFiles) {
		             String id = UUID.randomUUID().toString();
		            sb.append("<img src=\"cid:");
		            sb.append(id);
		            sb.append("\" alt=\"ATTACHMENT\"/>\n");
	
		            MimeBodyPart attachment = new MimeBodyPart();
		            DataSource fds = new FileDataSource(attachmentFileName);
		            attachment.setDataHandler(new DataHandler(fds));
		            attachment.setHeader("Content-ID", "<" + id + ">");
		            attachment.setFileName(fds.getName());
		            multipart.addBodyPart(attachment);
		        }
	        }
	    
		        // put everything together  
		        message.setContent(multipart);  
	
		        
			    message.setSentDate(new Date());
			    System.out.println("starting mail send to: " + to);
			    Transport.send(message);
			}
			catch (MessagingException me) {
				System.err.println(me.getMessage());
				}
			catch (FileNotFoundException e) {
				e.printStackTrace();
				} 
			catch (IOException e) {
				e.printStackTrace();
				}
			}
	
		///correct image src location
		private String imgSrcLoc(String sFoundImageLoc)	{
			String sImgSrcLoc = null;
			String sTagImageStart = ":///";
			
			int iTagImageStartIndex = sFoundImageLoc.indexOf(sTagImageStart); 
			sImgSrcLoc = sFoundImageLoc.substring(iTagImageStartIndex + 4, sFoundImageLoc.length()-2);
			sImgSrcLoc = sImgSrcLoc.replace("/", "\\\\");
			return sImgSrcLoc;
		}
		
	}
